package com.medvalley.tcm.service.impl;

import com.google.common.collect.Lists;
import com.medvalley.tcm.base.BusinessException;
import com.medvalley.tcm.dao.SleepDataDao;
import com.medvalley.tcm.domain.SleepData;
import com.medvalley.tcm.vo.inputvo.SleepDataInputVo;
import com.medvalley.tcm.vo.outputvo.SleepDataOutputVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
public class SleepDataService {

    @Autowired
    private SleepDataDao sleepDataDao;

    public void saveSleepData(long userId, SleepDataInputVo sleepDataInputVo) {
        //  一天只有一次睡眠记录
        SleepData sleepDataToday = sleepDataDao.findOneByUserIdAndRecordDate(userId, sleepDataInputVo.getRecordDate());
        if (sleepDataToday != null) {
            sleepDataDao.deleteById(sleepDataToday.getId());
        }
        SleepData sleepData = new SleepData();
        sleepData.setUserId(userId);
        BeanUtils.copyProperties(sleepDataInputVo, sleepData);
        sleepData.setCreateTime(new Date());
        sleepDataDao.save(sleepData);
    }

    public List<String> listSleepRecordDate(long userId) {
        List<String> sleepRecords = Lists.newArrayList();
        List<SleepData> sleepDataList = sleepDataDao.findAllByUserId(userId);
        if (CollectionUtils.isEmpty(sleepDataList)) {
            return sleepRecords;
        }
        sleepDataList.forEach(s -> sleepRecords.add(s.getRecordDate()));
        return sleepRecords;
    }

    public SleepDataOutputVo sleepDateDetail(long userId, String recordDate) {
        SleepData sleepDataToday = sleepDataDao.findOneByUserIdAndRecordDate(userId, recordDate);
        if (sleepDataToday == null) {
            throw new BusinessException("这一天没有睡眠数据");
        }
        SleepDataOutputVo sleepDataOutputVo = new SleepDataOutputVo();
        BeanUtils.copyProperties(sleepDataToday, sleepDataOutputVo);
        return sleepDataOutputVo;
    }

}
